/**
 * TradingView 加载器工具
 * 解决APP环境下TradingView无法加载的问题
 */

/**
 * 检测当前运行环境
 * @returns {Object} 环境信息
 */
export function getEnvironment() {
  let systemInfo = {}
  let platform = 'unknown'
  let userAgent = 'unknown'
  
  // 安全地获取系统信息
  try {
    if (typeof uni !== 'undefined' && uni.getSystemInfoSync) {
      systemInfo = uni.getSystemInfoSync()
      platform = systemInfo.platform || 'unknown'
      userAgent = systemInfo.userAgent || 'unknown'
    } else if (typeof window !== 'undefined' && window.navigator) {
      // H5环境下的fallback
      platform = 'web'
      userAgent = window.navigator.userAgent || 'unknown'
      systemInfo = {
        platform: 'web',
        userAgent: userAgent
      }
    }
  } catch (error) {
    console.warn('[TradingView] Failed to get system info:', error)
    // 使用默认值
    platform = 'web'
    userAgent = 'unknown'
    systemInfo = { platform: 'web', userAgent: 'unknown' }
  }
  
  // 更准确的环境检测
  const isApp = platform === 'android' || platform === 'ios'
  const isH5 = platform === 'devtools' || platform === 'web'
  const isAppPlus = platform === 'app-plus' || 
                    (typeof plus !== 'undefined') ||
                    (typeof window !== 'undefined' && window.plus)
  
  console.log('[TradingView] Environment detection:', JSON.stringify({
    platform,
    isApp,
    isH5,
    isAppPlus,
    userAgent,
    hasUni: typeof uni !== 'undefined',
    hasPlus: typeof plus !== 'undefined'
  }, null, 2))
  
  return {
    isApp: isApp || isAppPlus,
    isH5,
    isAppPlus,
    platform,
    userAgent,
    systemInfo
  }
}

/**
 * 获取TradingView脚本加载源
 * @returns {Array} 脚本源数组，按优先级排序
 */
export function getTradingViewSources() {
  const env = getEnvironment()
  
  // 统一使用本地资源，避免网络超时
  return [
    './charting_library/charting_library.min.js',
    '/charting_library/charting_library.min.js',
    '/utils/tv.js'
  ]
}

/**
 * 获取TradingView路径配置
 * @param {string} theme 主题名称
 * @returns {Object} 路径配置
 */
export function getTradingViewPathConfig(theme = 'light') {
  const env = getEnvironment()
  
  // 优先使用本地资源，避免网络超时
  return {
    library_path: './charting_library/',
    // 不设置custom_css_url，使用默认样式避免网络请求
    // custom_css_url: `../tradingview_${theme}.css`
  }
}

/**
 * 加载TradingView脚本
 * @returns {Promise} 加载Promise
 */
export function loadTradingViewScript() {
  return new Promise((resolve, reject) => {
    // 如果已经加载过，直接返回
    if (typeof TradingView !== 'undefined') {
      resolve()
      return
    }
    
    const sources = getTradingViewSources()
    let currentIndex = 0
    
    const tryLoadScript = () => {
      if (currentIndex >= sources.length) {
        console.error('All TradingView script sources failed to load')
        reject(new Error('All TradingView script sources failed to load'))
        return
      }
      
      const script = document.createElement('script')
      script.src = sources[currentIndex]
      
      console.log(`[TradingView] Trying to load from: ${sources[currentIndex]}`)
      
      script.onload = () => {
        // 等待一小段时间确保 TradingView 对象被正确初始化
        setTimeout(() => {
          if (typeof TradingView !== 'undefined') {
            console.log(`[TradingView] Loaded successfully from: ${sources[currentIndex]}`)
            resolve()
          } else {
            console.error(`[TradingView] Script loaded but TradingView is not defined from: ${sources[currentIndex]}`)
            currentIndex++
            tryLoadScript()
          }
        }, 100)
      }
      
      script.onerror = () => {
        console.error(`[TradingView] Failed to load from: ${sources[currentIndex]}`)
        currentIndex++
        tryLoadScript()
      }
      
      document.head.appendChild(script)
    }
    
    tryLoadScript()
  })
}

/**
 * 检查TradingView是否可用
 * @returns {boolean} 是否可用
 */
export function isTradingViewAvailable() {
  return typeof TradingView !== 'undefined'
}

/**
 * 获取TradingView错误信息
 * @returns {string} 错误信息
 */
export function getTradingViewErrorMessage() {
  const env = getEnvironment()
  
  if (env.isApp) {
    return 'Failed to load TradingView charting library. Please check your network connection or try again later.'
  } else {
    return 'Failed to load TradingView charting library. Please refresh the page and try again.'
  }
}
